package com.haiyou.dc.thread.test1;

public class Happy12306 {

    public static void main(String[] args) {
        Web12306 web12306 = new Web12306(5, "开心电影院");
        new Passager(web12306, "张三", 2).start();
        new Passager(web12306, "李四", 3).start();
    }
}

/**
 * 乘客
 */
class Passager extends Thread {

    public int seat;

    public Passager(Runnable target, String name, int seat) {
        super(target, name);
        this.seat = seat;
    }

}


/**
 * 12306购票
 */
class Web12306 implements Runnable {
    private int available;
    private String name;

    public Web12306(int available, String name) {
        this.available = available;
        this.name = name;
    }

    @Override
    public void run() {
        Passager passager = (Passager) Thread.currentThread();
        boolean flag = bookTicket(passager.seat);
        if (flag) {
            System.out.println(Thread.currentThread().getName() + ",购票成功...." + passager.seat);
        } else {
            System.out.println(Thread.currentThread().getName() + "购票失败....位置不够，购票数" + passager.seat);
        }

    }

    public synchronized boolean bookTicket(int seat) {
        System.out.println("-------->可用位置" + available);
        if (seat > available) {
            return false;
        }
        available -= seat;
        return true;
    }


}
